import 'package:flutter/material.dart';
import 'dart:async'; // 用于倒计时功能
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:provider/provider.dart';
import 'package:toys_flutter/store/app.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController(
    text: '18983425803', // 设置默认值
  );
  final TextEditingController _codeController = TextEditingController(
    text: '2024520', // 设置默认值
  );
  int client = 6;
  bool _isButtonDisabled = false;
  int _seconds = 60;
  Timer? _timer;
  bool _isChecked = false;

  void _startTimer() {
    TDToast.showIconText(
      '验证码发送成功',
      icon: TDIcons.check_circle,
      context: context,
    );
    setState(() {
      _isButtonDisabled = true;
      _seconds = 60;
    });
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_seconds > 0) {
          _seconds--;
        } else {
          _isButtonDisabled = false;
          _seconds = 60; // 重置倒计时
          _timer?.cancel();
        }
      });
    });
  }

  void _login() async {
    final String account = _phoneController.text;
    final String code = _codeController.text;

    if (_isChecked == false) {
      TDToast.showIconText('请同意协议',
          icon: TDIcons.error_circle, context: context);
      return;
    }
    if (account.isEmpty || code.isEmpty) {
      TDToast.showIconText('请输入手机号和验证码',
          icon: TDIcons.error_circle, context: context);
      return;
    }

    try {
      print('开始登录');
      var response = await Api.smsLogin(
          {'account': account, 'code': code, 'client': client});
      print(response);
      if (response['code'] == 1) {
        // 处理登录响应
        TDToast.showIconText(
          '登录成功',
          icon: TDIcons.check_circle,
          direction: IconTextDirection.vertical,
          context: context,
        );

        // 提取用户数据
        Map<String, dynamic> userData = response['data'];

        // 调用 AppState 的方法来更新用户数据
        final appState = Provider.of<AppState>(context, listen: false);
        appState.setToken(userData['token']);
        appState.setUserInfoAttribute('avatar', userData['avatar']);
        appState.setUserInfoAttribute('id', userData['id']);
        appState.setUserInfoAttribute('level', userData['level']);
        appState.setUserInfoAttribute('nickname', userData['nickname']);

        Future.delayed(const Duration(seconds: 1), () {
          Navigator.pushReplacementNamed(context, '/home');
        });
      } else {
        TDToast.showText(
          response['msg'],
          context: context,
        );
      }
    } catch (e) {
      print(e);
      TDToast.showText(
        '登录失败',
        context: context,
      );
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _phoneController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: const Color(0xFFE7E2FE), // 设置AppBar的背景色为蓝色，与渐变色相同
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFE7E2FE),
              Colors.white,
              Colors.white,
            ], // 设置渐变色数组
          ),
        ),
        child: Center(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const TDImage(
                      assetUrl: 'images/logo.png',
                      type: TDImageType.roundedSquare,
                    ),
                    // 添加Logo
                    const SizedBox(height: 80),
                    TextField(
                      controller: _phoneController,
                      keyboardType: TextInputType.phone,
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _codeController,
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              labelText: '验证码',
                              border: OutlineInputBorder(),
                            ),
                          ),
                        ),
                        const SizedBox(width: 8),
                        SizedBox(
                          width: 120, // 固定宽度
                          height: 40,
                          child: ElevatedButton(
                            onPressed: _isButtonDisabled ? null : _startTimer,
                            style: ElevatedButton.styleFrom(
                              foregroundColor: _isButtonDisabled
                                  ? Colors.grey
                                  : TDTheme.defaultData()
                                      .brandNormalColor, // 按钮文字颜色
                              backgroundColor: Colors.white, // 按钮背景色
                              side: BorderSide(
                                color: _isButtonDisabled
                                    ? Colors.grey
                                    : TDTheme.defaultData()
                                        .brandNormalColor, // 边框颜色
                                width: 1, // 边框宽度
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20), // 圆角边框
                              ),
                            ),
                            child: _isButtonDisabled
                                ? Text('$_seconds s')
                                : const Text(
                                    '获取验证码',
                                    style: TextStyle(fontSize: 12),
                                  ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 15),
                  ],
                ),
              ),
              TDButton(
                text: '登录',
                size: TDButtonSize.large,
                type: TDButtonType.fill,
                shape: TDButtonShape.rectangle,
                theme: TDButtonTheme.primary,
                isBlock: true,
                onTap: _login,
              ),
              // 同意协议
              Padding(
                padding: const EdgeInsets.all(15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Checkbox(
                      value: _isChecked,
                      onChanged: (bool? value) {
                        setState(() {
                          _isChecked = value ?? false;
                        });
                      },
                    ),
                    const Text(
                      '同意服务协议',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
              ),
              const Padding(
                padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      '未注册的手机号，登录后将自动注册',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
